extends CharacterBody2D

const JUMP_VELOCITY = -900.0
const EXTRA_SPEED = 120.0

@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var screen_size: Vector2 = get_viewport_rect().size;
@onready var jump_audio: AudioStreamPlayer = $JumpAudio


func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity += get_gravity() * delta

	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		jump_audio.play()

	var direction := Input.get_axis("move_left", "move_right")
	if direction:
		velocity.x = direction * (Global.speed + EXTRA_SPEED)
	else:
		velocity.x = move_toward(velocity.x, 0, Global.speed)

	animated_sprite.flip_h = direction == -1;

	move_and_slide()
	_update_animation(direction)
	
	position = position.clamp(Vector2.ZERO, screen_size);


func _update_animation(direction: float) -> void:
	if not is_on_floor():
		animated_sprite.play("fall")
	elif direction != 0:
		animated_sprite.play("walk")
	else:
		animated_sprite.play("idle")
	pass
